package config

import (
	"bufio"
	"dump/tools"

	"fmt"
	"os"
	"strings"
)

type MySQLConfig struct {
	Host          string
	Port          string
	User          string
	Password      string
	DumpPath      string
	Databases     []string
	Tables        []string
	Options       string
	BackupDir     string
	LogDir        string
	ExpireDays    int
	CompressLevel int
	BackupType    string
	NotifyEnable  bool
	NotifyAll     bool
	WebhookURL    string
	Secret        string
	Prompt        string
}

func ParseConfig(filePath string) (*MySQLConfig, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return nil, fmt.Errorf("配置文件打开失败: %v", err)
	}
	defer file.Close()
	config := &MySQLConfig{}
	scanner := bufio.NewScanner(file)

	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}

		parts := strings.SplitN(line, "=", 2)
		if len(parts) != 2 {
			continue
		}

		key := strings.TrimSpace(parts[0])
		value := strings.TrimSpace(parts[1])

		switch key {
		case "host":
			config.Host = value
		case "port":
			config.Port = value
		case "user":
			config.User = value
		case "password":
			config.Password = value
		case "mysqldump_path":
			config.DumpPath = value
		case "databases":
			if value != "" {
				config.Databases = strings.Split(value, ",")
			}
		case "tables":
			if value != "" {
				config.Tables = strings.Split(value, ",")
			}
		case "backup_options":
			config.Options = value
		case "backup_dir":
			config.BackupDir = value
		case "log_dir":
			config.LogDir = value
		case "expire_days":
			fmt.Sscanf(value, "%d", &config.ExpireDays)
		case "compress_level":
			fmt.Sscanf(value, "%d", &config.CompressLevel)
		case "backup_type":
			config.BackupType = value
		case "notify_enable":
			config.NotifyEnable = (value == "true" || value == "1")
		case "notify_all":
			config.NotifyAll = (value == "true" || value == "1")
		case "webhook_url":
			config.WebhookURL = value
		case "secret":
			config.Secret = value
		case "prompt":
			config.Prompt = value
		}
	}

	if _, err := tools.PathExists(config.DumpPath); err != nil {
		return nil, err
	}

	if _, err := tools.PathExists(config.BackupDir); err != nil {
		return nil, err
	}

	if _, err := tools.PathExists(config.LogDir); err != nil {
		return nil, err
	}

	if config.ExpireDays <= 0 {
		config.ExpireDays = 180
	}

	if config.CompressLevel < 0 || config.CompressLevel > 9 {
		config.CompressLevel = 6
	}

	if config.BackupType == "" {
		return nil, fmt.Errorf("backup_type 未指定")
	} else {
		if config.BackupType != "database" && config.BackupType != "table" && config.BackupType != "full" {
			return nil, fmt.Errorf("backup_type 参数错误(full/database/table)")
		}
	}
	return config, scanner.Err()
}
